<?php
/**
 * Created by jinqiang on 2024/5/30 13:47.
 * Copyright (c) 2024, Your Company. All rights reserved.
 */


namespace App\Http\Services\Produce;



use App\Http\Models\Mysql\SsyProcessingFactoryNameTable;
use App\Http\Models\Mysql\SsyStyleImagesTable;
use App\Http\Models\Mysql\StyleTable;
use App\Http\Repository\EqbRepository;
use App\Http\Repository\KingdeeRepository;
use App\Http\Repository\LogRepository;
use App\Http\Repository\OmsRepository;
use App\Http\Repository\WmsRepository;

class FactoryService
{
    public function search($param)
    {
        $conn = new SsyProcessingFactoryNameTable();
        if($param['factory_name'] ?? ""){
            $factoryName = $param['factory_name'];
            $conn = $conn->where(function ($query) use ($factoryName){
                $query->where('factory_name', 'like', "%".$factoryName."%")
                    ->orWhere('factory_name_jiancheng', 'like', "%".$factoryName."%");
            });
        }
        if($param['supplier_id'] ?? ""){
            $conn = $conn->where('supplier_id', $param['supplier_id']);
        }
        if(isset($param['tab']) && $param['tab'] != "all"){
            $tabs = explode(",", $param['tab']);
            $conn = $conn->whereIn('group', $tabs);
        }
        if(isset($param['status']) && $param['status'] != ""){
            $conn = $conn->where('status', (Int)$param['status']);
        }
        if($param['tag_number'] ?? ""){
            $conn = $conn->where('tag_number', $param['tag_number']);
        }
        if(isset($param['is_oms']) && $param['is_oms'] != ""){
            $conn = $conn->where('is_oms', (Int)$param['is_oms']);
        }
        if(isset($param['is_eqb']) && $param['is_eqb'] != ""){
            $isEqbStatus = (Int)$param['is_eqb'];
            $conn = $conn->where($isEqbStatus<=11?"kz_sing_status_eqb":"yxrg_sing_status_eqb", $isEqbStatus % 10);
        }
        $res = $conn->orderBy("id", "desc")->paginate((Int)$param['limit'])->toArray();
        return ['data' => $res['data'], 'total' => $res['total']];
    }

    public function searchPre($param)
    {
        $conn = (new StyleTable())->where('approval_state', 0);
        if($param['number'] ?? ""){
            if(preg_match("/^[a-zA-Z]/is", $param['number'])){
                $conn = $conn->where('number', 'like', $param['number']."%");
            }else{
                $conn = $conn->where('number', 'like', "%".$param['number']."%");
            }
        }
        if($param['factory_name'] ?? ""){
            $factoryObj = (new SsyProcessingFactoryNameTable())->where('factory_name', $param['factory_name'])->first(['factory_name', 'factory_name_jiancheng']);
            list($factoryName, $factoryShortName) = [
                $factoryObj->factory_name ?? $param['factory_name'],
                $factoryObj->factory_name_jiancheng ?? $param['factory_name']
            ];
            $conn = $conn->where(function ($query) use($factoryName, $factoryShortName){
                $query->where('f8_short', $factoryShortName)
                    ->orWhere('f9_short', $factoryShortName)
                    ->orWhere('f10_short', $factoryShortName)
                    ->orWhere('f11_short', $factoryShortName)
                    ->orWhere('f12_short', $factoryShortName)
                    ->orWhere('p12_short', $factoryShortName)
                    ->orWhere('f12', $factoryName);
            });
        }
        $res = $conn->orderBy("year", "desc")->orderBy("month", "desc")->orderBy("creation_time", "desc")->paginate((Int)$param['limit'])->toArray();
        $numbers = array_column($res['data'], 'number');
        //缩略图
        $imgRes = (new SsyStyleImagesTable())->whereIn('type_no', $numbers)->get(["type_no", "thumb_images"])->toArray();
        $imgs = array_column($imgRes, 'thumb_images', 'type_no');
        foreach ($res['data'] as &$item){
            $item['thumb_images'] = $imgs[$item['number']] ?? "";
        }
        unset($item);
        return [
            'data' => $res['data'],
            'total' => $res['total']
        ];
    }

    //预排设置
    public function savePre($param)
    {
        $param = json_decode($param, true);
        $data = [
            'f12_id' => empty($param['f12_short']) ? 0 : $param['f12_id'],
            'f12' => empty($param['f12_short']) ? "" : $param['f12'],
            'f12_short' => $param['f12_short'],
            'p12_id' => empty($param['p12_short']) ? 0 : $param['p12_id'],
            'p12_short' => $param['p12_short'],
            'f8_id' => empty($param['f8_short']) ? 0 : $param['f8_id'],
            'f8_short' => $param['f8_short']
        ];
        $resp = (new StyleTable())->updateData($param['style_id'], $data);
        $resp['data'] = $data;
        return $resp;
    }

    public function open($param)
    {
        $status = (Int)$param['status'];
        $id = (Int)$param['id'];
        return (new SsyProcessingFactoryNameTable())->updateData($id, ['status' => $status]);
    }

    public function push($supplierId)
    {
        $fatoryObj = (new SsyProcessingFactoryNameTable())->where('supplier_id', $supplierId)->first()->toArray();
        //推送巨益
        list($omsRes, $pushData) = OmsRepository::pushFactory($fatoryObj);
        // 推送巨沃
        $wmsRes = WmsRepository::pushFactory($fatoryObj);
        //推送金蝶
        $kingRes = KingdeeRepository::pushFactory($fatoryObj);
        if($wmsRes['success'] && $omsRes['success']){
            LogRepository::setJuyiPushLog($pushData,1,'创建供应商', auth()->guard("api")->user()->name); //存入日志
            return (new SsyProcessingFactoryNameTable())->updateData($fatoryObj['id'], ['is_oms' => 1]);
        }else{
            return ['code' => -1, 'msg' => '推送失败', 'data' => ['oms' => $omsRes, 'wms' => $wmsRes, 'king' => $kingRes]];
        }
    }

    public function save($data)
    {
        $data = json_decode($data, true);
        if(empty($data['factory_name']) || empty($data['factory_name_jiancheng']) || empty($data['contact_address']) || empty($data['legal_person'])
            || empty($data['contact_phone'])){
            return ['code' => -1, 'msg' => '必填内容不能为空'];
        }
        $id = $data["id"] ?? "";
        $factoryNames = config("scm.factory_type");
        $saveData = [
            'factory_name' => $data['factory_name'],
            'factory_name_jiancheng' => $data['factory_name_jiancheng'] ?? "",
            'group' => $data['group'],
            'group_name' => $factoryNames[$data['group']],
            'is_advance' => $data['is_advance'],
            'bank_of_deposit' => $data['bank_of_deposit'],
            'opening_bank_no' => $data['opening_bank_no'],
            'company_head' => $data['company_head'],
            'tag_number' => $data['tag_number'],//吊牌编号
            'company_qualification' => $data['company_qualification'],
            'bank_account' => $data['bank_account'],
            'tax_rate' => $data['tax_rate'],
            'legal_person' => $data['legal_person'],
            'contact_phone' => $data['contact_phone'],
            'contact_address' => $data['contact_address'],
            'is_free' => $data['is_free'],
            'pinyin_name' => $data['pinyin_name'] ?: "",
            'business_license' => $data['business_license'],
            'eqb_user' => $data['eqb_user'] ?: "",
            'eqb_phone' => $data['eqb_phone'] ?: "",
            'eqb_card' => $data['eqb_card'] ?: "",
            'certificate_no' => $data['certificate_no'] ?: "",
            'createtime' => date('Y-m-d H:i:s')
        ];
        if(!empty($id)){
            unset($saveData['createtime']);
            $exist = (new SsyProcessingFactoryNameTable())->where('id', '<>', $id)->where('factory_name', $saveData['factory_name'])->exists();
            if($exist){
                return ['code' => -1, 'msg' => '工厂名称已经存在, 请换一个名称'];
            }
            return (new SsyProcessingFactoryNameTable())->updateData($id, $saveData);
        }else{
            $factoryObj = (new SsyProcessingFactoryNameTable())->orderBy('id', 'desc')->first(['id']);
            $saveData['supplier_id'] = "1".($factoryObj->id+1);
            $exist = (new SsyProcessingFactoryNameTable())->where('factory_name', $saveData['factory_name'])->exists();
            if($exist){
                return ['code' => -1, 'msg' => '工厂名称已经存在, 请换一个名称'];
            }
            return (new SsyProcessingFactoryNameTable())->createData($saveData);
        }
    }

    public function openEqb($supplierId, $type)
    {
        $factoryObj = (new SsyProcessingFactoryNameTable())->where('supplier_id', $supplierId)->first()->toArray();
        if(empty($factoryObj['opening_bank_no']) || empty($factoryObj['legal_person']) || empty($factoryObj['company_head']) ||empty($factoryObj['certificate_no'])
            || empty($factoryObj['eqb_user']) || empty($factoryObj['eqb_phone']) || empty($factoryObj['eqb_card'])){
            return ['code' => -1, 'msg' => '请确保E签宝开通参数正常'];
        }
        //创建企业号
        $organizationsData = [
            'thirdPartyUserId' => $factoryObj['certificate_no'], //创建机构账号的唯一标识。可将企业证件号、企业邮箱地址等作为此账号的唯一标识。
            'idType' => 'CRED_ORG_USCC',//机构名称
            'name' => $factoryObj['company_head'],//机构名称
            'idNumber' => $factoryObj['certificate_no'],//社会统一代码
        ];
        $organizationsRes = (new EqbRepository($type))->createOrganizations($organizationsData);
        //创建个人号
        $accountsData = [
            'thirdPartyUserId' => $factoryObj['eqb_card'],//证件号。
            'idType' => "CRED_PSN_CH_IDCARD",//证件类型，默认CRED_PSN_CH_IDCARD
            'idNumber' => $factoryObj['eqb_card'],//证件号
            'name' => $factoryObj['eqb_user'],//姓名
            'mobile' => $factoryObj['eqb_phone'],//姓名
        ];
        $accountsRes = (new EqbRepository($type))->createAccounts($accountsData);
        if(in_array($organizationsRes['code'], [0, 53000000]) && in_array($accountsRes['code'], [0, 53000000])){
            $prefix = $type == 'yx' ? "yxrg" : $type;
            $data = [
                $prefix.'_signerorgid' => $organizationsRes['data']['orgId'],
                $prefix.'_signeraccountid' => $organizationsRes['data']['accountId'],
                $prefix.'_signer_user_accountid' => $accountsRes['data']['accountId'],
                $prefix.'_sing_status_eqb' => 1
            ];
            return (new SsyProcessingFactoryNameTable())->updateDataWhere(['supplier_id' => $supplierId], $data);
        }
        return ['code' => -1, 'msg' => 'E签宝开通失败', 'data' => [$accountsRes, $organizationsRes]];
    }
}
